//
//  StringHelper.m
//
//  Created by ZhàoYǒng on 23/10/2017.
//  Copyright © 2017 ZhàoYǒng. All rights reserved.
//

#import "StringHelper.h"
#import <CommonCrypto/CommonDigest.h>

@implementation StringHelper

NSString * _Nonnull StringFromObject(id _Nullable object) {
    if ([object isKindOfClass: NSString.class]) return object;
    if ([object isKindOfClass: NSNumber.class]) {
        return [NSString stringWithFormat:@"%@", object];
    }
    if ([object isKindOfClass: NSData.class]) {
        return [[NSString alloc] initWithData:object encoding:NSUTF8StringEncoding];
    }
    return nil;
}

NSString * _Nullable StringGetPinyin(NSString * _Nullable string, BOOL isTone) {
    NSMutableString *mutableString = [NSMutableString stringWithString:string];
    if (isTone) {
        CFStringTransform((CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, false);
    }else {
        CFStringTransform((CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, false);
        CFStringTransform((CFMutableStringRef)mutableString, NULL, kCFStringTransformStripDiacritics, false);
    }
    
    NSString *PinyinStr = [mutableString stringByReplacingOccurrencesOfString:@" " withString:@""];
    return PinyinStr;
}

NSString * _Nullable StringGetMD5(NSString * _Nullable string) {
    if(!StringIsValid(string)) return nil;
    
    const char *value = [string UTF8String];
    
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, (CC_LONG)strlen(value), outputBuffer);
    
    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
        [outputString appendFormat:@"%02x",outputBuffer[count]];
    }
    
    return outputString;
}

NSString * _Nullable StringGetComparedTime(NSString * _Nullable string) {
    //把字符串转为NSdate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *timeDate = [dateFormatter dateFromString:string];
    
    //得到与当前时间差
    NSTimeInterval  timeInterval = [timeDate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    //标准时间和北京时间差8个小时
    //timeInterval = timeInterval - 8*60*60;
    long temp = 0;
    NSString *result;
    if (timeInterval < 60) {
        result = [NSString stringWithFormat:@"刚刚"];
    }
    else if((temp = timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%ld分钟前",temp];
    }
    
    else if((temp = temp/60) <24){
        result = [NSString stringWithFormat:@"%ld小时前",temp];
    }
    
    else if((temp = temp/24) <30){
        result = [NSString stringWithFormat:@"%ld天前",temp];
    }
    
    else if((temp = temp/30) <12){
        result = [NSString stringWithFormat:@"%ld月前",temp];
    }
    else{
        temp = temp/12;
        result = [NSString stringWithFormat:@"%ld年前",temp];
    }
    
    return  result;
}

NSString * _Nullable StringGetComparedDetailTime(NSTimeInterval time1970) {
    
    NSDate *timeDate = [NSDate dateWithTimeIntervalSince1970:time1970];
    //得到与当前时间差
    NSTimeInterval  timeInterval = [timeDate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    //标准时间和北京时间差8个小时
    //timeInterval = timeInterval - 8*60*60;
    long temp = 0;
    NSString *result;
    
    if ((temp = (timeInterval/60/60)/24) < 1) {
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"a HH:mm"];
        
        result = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:timeDate]];
    }
    else if((temp = temp/24) == 1) {
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm a"];
        
        result = [NSString stringWithFormat:@"昨天 %@",[dateFormatter stringFromDate:timeDate]];
    }
    else if((temp = temp/30) >= 12 ) {
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        
        result = [dateFormatter stringFromDate:timeDate];
    }
    else {
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MM-dd HH:mm"];
        
        result = [dateFormatter stringFromDate:timeDate];
    }
    
    return  result;
}

BOOL StringIsValid(id _Nullable string) {
    if (!string) return NO;
    if (![string isKindOfClass:NSString.class]) return NO;
    return YES;
}
// 验证手机号
BOOL StringIsValidMobile(NSString * _Nullable mobile) {
    if (!StringIsValid(mobile)) return NO;
    if (mobile.length != 11) return NO;
    NSString *patternCellphone =  @"^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";
    NSRegularExpression *regexCellphone = [NSRegularExpression regularExpressionWithPattern:patternCellphone options:0 error:nil];
    NSTextCheckingResult *isMatchCellphone = [regexCellphone firstMatchInString:mobile options:0 range:NSMakeRange(0, mobile.length)];
    return isMatchCellphone ? YES : NO;
}
// 验证密码
BOOL StringIsValidLength(NSString * _Nullable string, NSInteger min, NSInteger max) {    return (string.length >= min && max >= string.length);
}

// 验证电子邮箱
BOOL StringIsValidEmail(NSString * _Nullable email) {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}
// 验证是否是数字
BOOL StringIsValidNumber(NSString * _Nullable string) {
    if (string.length == 0) return NO;
    NSString *regex =@"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:string];
}
// 验证是否是数字或字母
BOOL StringIsValidLetterOrNumber(NSString * _Nullable string) {
    if (string.length == 0) return NO;
    NSString *regex =@"[a-zA-Z0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:string];
}
/// 验证是否是同时包含数字和字母
BOOL StringIsValidLetterAndNumber(NSString * _Nullable string) {
    if (string.length < 2) return NO;
    NSString *regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{2,100}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL valid = [pred evaluateWithObject:string];
    return valid;
}
// 验证是否包含汉字
BOOL StringHasChinese(NSString *_Nullable string) {
    for (int i = 0; i < string.length; i++) {
        NSRange range = NSMakeRange(i, 1);
        NSString *subString = [string substringWithRange:range];
        if (!StringIsValid(subString)) {
            continue;
        }
        const char *cString = [subString UTF8String];
        if (strlen(cString) == 3) {
            return YES;
        }
        /*
         int a = [strtemp characterAtIndex:i];
         if( a > 0x4e00 && a < 0x9fff) {
         return YES;
         }
         */
    }
    return NO;
}
// 获取两个字符串的相似度
float StringLikePercent(NSString * _Nullable ori, NSString * _Nullable target) {
    NSUInteger n = ori.length;
    NSUInteger m = target.length;
    if (m==0) return n;
    if (n==0) return m;
    
    //Construct a matrix, need C99 support
    int matrix[n+1][m+1];
    memset(&matrix[0], 0, m+1);
    for(int i=1; i<=n; i++) {
        memset(&matrix[i], 0, m+1);
        matrix[i][0]=i;
    }
    for(int i=1; i<=m; i++) {
        matrix[0][i]=i;
    }
    for(int i=1;i<=n;i++) {
        unichar si = [ori characterAtIndex:i-1];
        for(int j=1;j<=m;j++)
        {
            unichar dj = [target characterAtIndex:j-1];
            int cost;
            if(si==dj){
                cost=0;
            }
            else{
                cost=1;
            }
            const int above=matrix[i-1][j]+1;
            const int left=matrix[i][j-1]+1;
            const int diag=matrix[i-1][j-1]+cost;
            matrix[i][j]=MIN(above,MIN(left,diag));
        }
    }
    
    return 100.0 - 100.0*matrix[n][m]/ori.length;
}

@end
